package com.xjtu.duansheli.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xjtu.duansheli.entity.ArticleInfo;
import com.xjtu.duansheli.entity.ProductInfo;
import com.xjtu.duansheli.exception.MyException;
import com.xjtu.duansheli.mapper.ArticleInfoMapper;
import com.xjtu.duansheli.service.ArticleInfoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 漩涡鸣人
 * @since 2020-10-24
 */
@Service
public class ArticleInfoServiceImpl extends ServiceImpl<ArticleInfoMapper, ArticleInfo> implements ArticleInfoService {

    @Autowired
    private ArticleInfoMapper articleInfoMapper;

    @Override
    public List<ArticleInfo> getAllArticle(int current, int size) {
        Page<ArticleInfo> page = new Page<>(current,size);
        articleInfoMapper.selectPage(page, null);
        System.out.println(page.getTotal());
        return page.getRecords();
    }

    @Override
    public ArticleInfo getArticleByid(Long aid) {
        ArticleInfo articleInfo = articleInfoMapper.selectById(aid);
        if(articleInfo == null){
            throw new MyException(500,"不存在该帖子！");
        }
        return articleInfo;
    }

    @Override
    public int addArticle(ArticleInfo article) {
        try{
            return articleInfoMapper.insert(article);
        }catch (Exception e){
            e.printStackTrace();
            throw new MyException(500,"添加帖子失败！");
        }
    }

    @Override
    public int updateArticle(ArticleInfo article) {
        try{
            return articleInfoMapper.updateById(article);
        }catch (Exception e){
            e.printStackTrace();
            throw new MyException(500,"修改帖子失败！");
        }
    }

    @Override
    public int deleteArticle(Long aid) {
        try{
            return articleInfoMapper.deleteById(aid);
        }catch (Exception e){
            e.printStackTrace();
            throw new MyException(500,"删除帖子失败！");
        }
    }

    @Override
    public List<ArticleInfo> getArticleByuid(Long uid) {
        HashMap<String, Object> map = new HashMap<>();
        map.put("author_id",uid);

        List<ArticleInfo> articleInfos = articleInfoMapper.selectByMap(map);
        if(articleInfos.size() == 0){
            throw new MyException(500,"该用户未发布任何帖子！");
        }
        return articleInfos;
    }

    @Override
    public int getTotal() {
        return articleInfoMapper.selectCount(null);
    }
}
